package com.wg.neptune.jackson;

import com.wg.neptune.ISerializer;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

/**
 * Created by mc on 18/5/16.
 */
public class JacksonSerializer implements ISerializer {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 初始化ObjectMapper
     * @return
     */
    private static  ObjectMapper getObjectMapper(){
        if(objectMapper != null){
            return objectMapper;
        }else {
            return new ObjectMapper();
        }
    }
    /**
     * Jackson序列化
     * @param obj
     * @param <T>
     * @return
     */
    public <T> byte[] serialize(T obj) {
        try {
            if(obj == null){
                return new byte[0];
            }
            String json = getObjectMapper().writeValueAsString(obj);
            return json.getBytes();
        } catch (IOException e) {
            throw  new RuntimeException(e.getMessage());
        }
    }

    /**
     * 反序列化 jackson
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        try {
            String json = new String(data);
            return (T)getObjectMapper().readValue(json,clazz);
        } catch (IOException e) {
            throw  new RuntimeException(e.getMessage());
        }
    }

    static class Person{
        private String name;
        private String sex;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }
    }

    /**
     * 序列化测试
     * @param args
     */
    public static void main(String[] args) {

        Person person = new Person();
        person.setName("wg");
        person.setSex("man");

        JacksonSerializer jacksonSerializer = new JacksonSerializer();
        byte[] perseri =  jacksonSerializer.serialize(person);

        System.out.print("序列化长度"+perseri.length);

        Person person1 = jacksonSerializer.deserialize(perseri,Person.class);

        System.out.print("反序列化："+person1.getName()+person1.getSex());
    }
}
